<?php

namespace common\modules\sms\components;

use Yii;

class LuosimaoSmser extends \daixianceng\smser\LuosimaoSmser
{

    /**
     * @inheritdoc
     */
    public function send($mobile, $content)
    {
        $data = [
            'mobile'  => $mobile,
            'message' => $content . $this->signature,
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->getUrl());
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);

        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_USERPWD, $this->username . ':' . $this->password);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        $result = curl_exec($ch);
        curl_close($ch);

        Yii::info('发送请求并获取返回值:' . json_encode([
                'url' => $this->getUrl(),
                'data' => $data,
                'result' => $result,
            ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), __METHOD__);

        if (empty($result))
        {
            $this->message = '网络错误';
        }
        else
        {
            if ($this->dataType === 'json')
            {
                $json = json_decode($result);
                if ($json && is_object($json))
                {
                    $this->state = isset($json->error) ? (string) $json->error : null;
                    $this->message = isset($json->msg) ? (string) $json->msg : null;
                }
            }
            else
            {
                $xml = simplexml_load_string(trim($result, " \t\n\r"));
                if ($xml && is_object($xml))
                {
                    $this->state = isset($xml->error) ? (string) $xml->error : null;
                    $this->message = isset($xml->msg) ? (string) $xml->msg : null;
                }
            }
        }

        return $this->state === '0';
    }
}
